package com.example.sqlitedemo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.util.List;

public class MainActivity extends AppCompatActivity {
    Button button_add, button_deleteall;
    RecyclerView recyclerView;
    Context context;
    List<ContactBean> list;
    MyRVAdapter rvAdapter;
    RecyclerView.LayoutManager layoutManager;
    ContactDBAdapter dbAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();//初始化控件
        context = MainActivity.this;

        //获取ContactDBAdapter的实例？？
        dbAdapter=ContactDBAdapter.getInstance(context);
        //打开数据库？？
        dbAdapter.openDB();
        //读取数据库的数据，形成list？？
        list=dbAdapter.queryAll();

        rvAdapter = new MyRVAdapter(context, list);
        layoutManager = new LinearLayoutManager(context);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(rvAdapter);
    }

    //初始化控件
    void initView() {
        button_add = (Button) findViewById(R.id.button_contact_add);
        button_deleteall = (Button) findViewById(R.id.button_contact_deleteall);
        button_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(context, AddContactActivity.class);
                startActivity(intent1);
            }
        });
        button_deleteall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //从数据库中删除所有数据
                dbAdapter.deleteAll();;
                //清空list
                list.clear();
                //通知listview数据刷新
                rvAdapter.setList(list);
            }
        });
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

    }

    //生命周期方法，该activity与用户能进行交互时被执行，本例由AddContactActivity返回时执行
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        //读取数据库的数据，重新生成list
        list=dbAdapter.queryAll();
        //更新adapter中的list对象
        rvAdapter.setList(list);
        //通知listview数据刷新

    }

    //生命周期方法，当系统销毁了这个Activity的实例在内存中占据的空间时执行
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if(dbAdapter!=null)
            dbAdapter.closeDB();//关闭数据库的操作
    }

}
